package com.example.demo.filter;


import com.example.demo.entity.Result;
import com.example.demo.exception.LoginException;
import com.example.demo.utils.token.TokenUtil;
import lombok.SneakyThrows;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter extends OncePerRequestFilter {

//    @SneakyThrows(LoginException.class)
    @Override
    @ResponseBody
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if ( httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name()) ) {
            filterChain.doFilter(httpServletRequest,response);
            return;
        }



        //允许跨域访问，通过response对象写回一些跨域访问的头信息
        response.setHeader("Access-Control-Allow-Origin", "*");
        //允许请求的方法
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
        response.setHeader("Access-Control-Expose-Headers", "Token");
        response.setHeader("Access-Control-Allow-Headers", "Token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String token = httpServletRequest.getHeader("Token");
        //添加这行代码，让OPTIONS请求通过
        if (token == "" || token.equals("") || token == null){
            return;
        }

        boolean checkToken = TokenUtil.checkToken(token);
        if (!checkToken) {
            response.setHeader("Token","false");
//            throw new LoginException("token错误，可能被篡改");
            return;
        }
        boolean checkTokenTime = TokenUtil.checkOverTime(token);
        if (!checkTokenTime) {
//            return Result.error("Token过期");
            response.setHeader("Token","timeOut");
//            throw new LoginException("Token过期");
            return;
        }

//        //设置跨域访问
//        httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
//        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin"));
//        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET");
//        httpServletResponse.addHeader("Access-Control-Expose-Headers","Token");



        //验证都通过设置新的token
        String newToken = TokenUtil.createNewToken(token);
        response.setHeader("Token", newToken);
        String id = TokenUtil.getId(token);
        httpServletRequest.setAttribute("id", id);

        filterChain.doFilter(httpServletRequest, response);
//        return null;
    }


}
